

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


/**
 * @Auther:
 * @Date: 2022/4/17 - 04 - 17 - 21:03
 * @Description: 坦克大战.事件处理机制
 * @version: 1.0
 */
public class BallMove extends JFrame{
    ball_panel ball_panel = null;

    public static void main(String[] args) {
        BallMove ballmove = new BallMove();
    }

    //构造器
    public BallMove(){
        ball_panel = new ball_panel();
        this.add(ball_panel);
        this.setSize(400,300);
        this.addKeyListener(ball_panel);    //在画板上监听键盘事件
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
    //  keylistener 键盘监听机制
    class ball_panel extends JPanel implements KeyListener {
        int x = 10;
        int y = 10;
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.fillOval(x,y,20,20);
        }

        //有字符输出时，该方法触发
        @Override
        public void keyTyped(KeyEvent event) {

        }
        //当某个按键按下，该方法会被触发
        @Override
        public void keyPressed(KeyEvent event) {
            //根据不同的按键输入控制小球移动
            if(event.getKeyCode() == KeyEvent.VK_DOWN) {     //检测向下键是否被按下
                y++;
            }
            else if(event.getKeyCode() == KeyEvent.VK_UP){		//向上
                y--;
            }
            else if(event.getKeyCode() == KeyEvent.VK_RIGHT){	//向右
                x++;
            }
            else if(event.getKeyCode() == KeyEvent.VK_LEFT){	//向左
                x--;
            }
            this.repaint();
        }
        //某个按键松开，该方法会被触发
        @Override
        public void keyReleased(KeyEvent event) {

        }
    }
}
